﻿angular.module('Caltech').controller('standardItemController', function (
			$scope, Restangular, $state, $stateParams, $filter, Statuses, $window, $location, Constants) {
    'use strict';

    $scope.model = {
        createdBy: Constants.accountInfo.id,
        updatedBy: Constants.accountInfo.id,
        technicianName: Constants.accountInfo.fullName
    };

    if ($stateParams.id) {
        Restangular.one('standard', $stateParams.id).get().then(function (model) {
            $scope.model = model;
        });
    }

    if ($stateParams.model) {
        $scope.model = JSON.parse($stateParams.model);
    }

    $scope.update = function (model) {
        model.updatedBy = Constants.accountInfo.id;
        if (Constants.accountInfo)
            model.technicianName = Constants.accountInfo.fullName;
        return model.put({ id: model.certificateStandardId }).then(function () {
            $state.forceReload();
        });
    };

    $scope.save = function (model) {
        model.createdBy = Constants.accountInfo.id;
        return Restangular.all('standard').post(model).then(function (id) {
            $state.go('standard-item', { id: id });
        });
    };

    $scope.copy = function () {
        var model = Restangular.stripRestangular($scope.model);
        model.certificateStandardId = undefined;
        $state.go('standard-new', {
            model: JSON.stringify(model)
        });
    };

    $scope.remove = function (model) {
        return model.remove({ id: model.certificateStandardId }).then(function () {
            history.back();
        });
    };

    $scope.doPrint = function () {
        $window.print();
        $location.reload();
    };

    $scope.statuses = Statuses;

    $scope.showStatus = function (value) {
        var result = '';
        if (value) {
            var selected = $filter('filter')($scope.statuses, { value: value });

            if (selected.length) {
                result = selected[0].text;
            }
        }
        return result;
    };
});